package pps.et5.eit.ex4;

import java.util.Scanner;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.TextMessage;
import javax.naming.InitialContext;

import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jms.JmsComponent;
import org.apache.camel.component.jms.JmsConsumer;
import org.apache.camel.component.jms.JmsEndpoint;
import org.apache.camel.component.jms.JmsExchange;
import org.apache.camel.impl.DefaultCamelContext;

public class ClientCamel {
	private static ConnectionFactory connectionFactory;
	
	public ConnectionFactory getConnectionFactory() {
		return connectionFactory;
	}
	
	// Méthode de connection
	private void connect() throws Exception {
		// Initialise les attributs connectionFactory et destination.
		// Création d'un contexte JNDI
		InitialContext jndiContext = new InitialContext();
		// Lookup de la fabrique de connexion et de la destination
		connectionFactory = (ConnectionFactory) jndiContext.lookup("connectionFactory");
	}
	
	// Main
	public static void main(String[] args) { 
		try {
			String smes = new String();
			final ClientCamel clientcamel = new ClientCamel();
			clientcamel.connect();
		
			System.out.println("Connection effectuée");
			
			CamelContext context = new DefaultCamelContext(); 
			context.addComponent("jms-test", JmsComponent.jmsComponentAutoAcknowledge(clientcamel.getConnectionFactory()));
			
			ProducerTemplate<JmsExchange> pt = context.createProducerTemplate();
			
			context.start();
			
			System.out.println("Taper l'id de l'article (Q pour quitter)");
			
			Scanner inputStream = new Scanner(System.in);
			JmsEndpoint responseEndPoint = (JmsEndpoint) context.getEndpoint("jms-test:fournisseur.responseQueue");
			
			JmsConsumer consumer = responseEndPoint.createConsumer(new Processor() { 
				public void process(Exchange e) throws Exception {
					System.out.println("Réponse reçue : " + e.getIn().getBody()); 
				}
			});
			
			consumer.start();
			
			// Attente d'entrées par l'utilisateur tant qu'il ne tape pas Q
			while ( !(smes.compareTo("Q") == 0) ) {
				smes = inputStream.nextLine();
				pt.sendBody("jms-test:fournisseur.requestQueue",smes);
				
			}
			
		} catch (Throwable t) { 
			t.printStackTrace();
		} 

	}
}
